package com.example.demo.common.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.common.config.AppConfig;
import com.example.demo.common.enums.CodeEnum;
import com.example.demo.common.exception.BaseRuntimeException;
import com.example.demo.common.result.R;
import com.example.demo.common.utils.JwtUtil;
import com.example.demo.service.UserTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 过滤器
 */
@Component
@Slf4j
public class MyFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserTService userTService;

    private AppConfig appConfig;

    private Set<String> whiteListSet;

    public Set<String> getWhiteListSet() {
        Set<String> objects = new HashSet<>();
        objects.add("/login");
        return this.whiteListSet = objects;
    }

    @Autowired
    public void setAppConfig(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化
        System.out.println("MyFilter initialized");
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        try {
            // token解析
            for (String s : getWhiteListSet()) {
                if (!s.equals(httpServletRequest.getRequestURI())) {
                    handToken(httpServletRequest);
                }
            }
            chain.doFilter(request, response); // 继续处理请求
        } catch (BaseRuntimeException e) {
            handleBaseRuntimeException(httpServletResponse, e);
        }
    }

    /**
     * 校验token
     * @param httpServletRequest
     */
    private void handToken(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("fuck-token");
//        userTService.checkToken(token);
//        if (jwtUtil.validateToken(token.replace("Bearer ", ""))) {
//            String username = jwtUtil.getUsernameFromToken(token.replace("Bearer ", ""));
//            log.info("validate success --- {}", username);
//        } else {
//            throw new BaseRuntimeException(CodeEnum.FAILTOKEN.getCode(), "token校验失败");
//        }
        if (!StringUtils.equals(token, "szb.nb")) {
            throw new BaseRuntimeException(CodeEnum.FAILTOKEN.getCode(), "token校验失败");
        }

    }

    /**
     * 处理异常
     * @param response
     * @param ex
     * @throws IOException
     */
    private void handleBaseRuntimeException(HttpServletResponse response, BaseRuntimeException ex) throws IOException {
        response.setStatus(ex.getCode());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 处理BaseRuntimeException异常
        String jsonString = R.fail(ex.getCode(), ex.getMessage()).toJsonString();
        response.getWriter().write(jsonString);

    }

    @Override
    public void destroy() {
        // 销毁
        System.out.println("MyFilter destroyed");
    }


}
